import { Injectable } from '@nestjs/common';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import * as dayjs from 'dayjs';
import UserLittleThingsExtendEntity from 'src/entities/user-little-things-extend.entity';
import UserLittleThingsImageEntity from 'src/entities/user-little-things-image.entity';
import UserLittleThingsEntity from 'src/entities/user-little-things.entity';
import { uploadFile } from 'src/utils/file';
import { computeWeekly } from 'src/utils/loveDay';
import { EntityManager, Repository } from 'typeorm';
import { CompleteUserLittleThingsDTO, GetCompletedUserLittleThingsInfoDTO, GetUserLittleThingsDTO } from './little-things.dto';

@Injectable()
export class LittleThingsService {
  constructor(
    @InjectRepository(UserLittleThingsEntity)
    private readonly userLittleThingsEntityRepository: Repository<UserLittleThingsEntity>,
    @InjectRepository(UserLittleThingsImageEntity)
    private readonly userLittleThingsImageEntityRepository: Repository<UserLittleThingsImageEntity>,
    @InjectEntityManager() private entityManager: EntityManager,
  ){}

  async getUserLittleThings(getUserLittleThings:GetUserLittleThingsDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1,ThingsType='all'}=getUserLittleThings;
      
      let where=''
      if(ThingsType==='complete'){
        where=` AND T.IsCompleted=1 `
      }
      else if(ThingsType==='unComplete'){
        where=` AND T.IsCompleted=0 `
      }

      const thingsList=await this.userLittleThingsEntityRepository  
        .createQueryBuilder('T')
        .select([
          'T.SysID SysID','T.ThingName ThingName','T.ThingContent ThingContent',`T.IsCompleted IsCompleted`,
          `CASE WHEN IFNULL(TE.CompleteImageUrl,'')='' THEN T.ImageUrl ELSE TE.CompleteImageUrl END ImageUrl`,
          `IFNULL(TE.Weekly,'') Weekly`,`IFNULL(TE.CompleteDay,'') CompleteDay`,`IFNULL(TE.CompleteYearAndMonth,'') CompleteYearAndMonth`
        ])
        .leftJoin('UserLittleThingsExtend','TE','T.SysID=TE.LittleSysID AND TE.Deleted=0')
        .where(`T.Deleted=0 AND T.UserSysID=:UserSysID ${where}`,{UserSysID:UserSysID})
        .orderBy('T.SysID')
        .getRawMany();
      const count=await this.userLittleThingsEntityRepository.query(`
        SELECT SUM(E.AllCount) AllCount,SUM(E.Complete) Complete,SUM(E.UnComplete) UnComplete
        FROM (
          SELECT COUNT(*) AllCount,0 Complete,0 UnComplete
          FROM UserLittleThings
          WHERE Deleted=0 AND UserSysID=${UserSysID}
          UNION 
          SELECT 0 AllCount,COUNT(*)  Complete,0 UnComplete
          FROM UserLittleThings
          WHERE Deleted=0 AND UserSysID=${UserSysID} AND IsCompleted=1
          UNION 
          SELECT 0 AllCount, 0 Complete,COUNT(*) UnComplete
          FROM UserLittleThings
          WHERE Deleted=0 AND UserSysID=${UserSysID} AND IsCompleted=0
        ) E
      `)
      let thingsCount={
        AllCount:0,
        Complete:0,
        UnComplete:0
      }
      if(count.length>0){
        thingsCount=count[0]
      }
      resData.data={
        thingsList:thingsList,
        thingsCount:thingsCount
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取清单失败!'
      }
    }
    return resData
  }

  async completeUserLittleThings(completeUserLittleThings:CompleteUserLittleThingsDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {
        SysID=-1,CompleteTime='',CompleteAddress='',ThingContent='',ImageData=[]
      }=completeUserLittleThings;
      const now=dayjs().format('YYYY-MM-DD HH:mm:ss')
      await this.entityManager.transaction(async entityManager=>{

        //#region 更新UserLittleThings表
        const newUserLittleThingsEntity=new UserLittleThingsEntity()
        newUserLittleThingsEntity.Edited=1;
        newUserLittleThingsEntity.IsCompleted=1;
        newUserLittleThingsEntity.ThingContent=ThingContent;
        newUserLittleThingsEntity.UpdateTime=now;
        await entityManager.update(UserLittleThingsEntity,{
          SysID:SysID
        },newUserLittleThingsEntity)
        //#endregion

        //#region 插入UserLittleThingsImage表
        let completeImageUrl = '';
        let sort = 0;
        for (const item of ImageData) {
          sort=sort+1;
          const resImageUrl=await uploadFile(item,'base64','littleThings/') as {code:number,data:any,msg:string};
          if(resImageUrl.code===200){
            const newUserLittleThingsImageEntity=new UserLittleThingsImageEntity();
            newUserLittleThingsImageEntity.LittleSysID=SysID;
            newUserLittleThingsImageEntity.ImageUrl='http://'+resImageUrl.data.ImageUrl;
            newUserLittleThingsImageEntity.Sort=sort;
            newUserLittleThingsImageEntity.CreateTime=now;
            newUserLittleThingsImageEntity.UpdateTime=now;
            newUserLittleThingsImageEntity.Deleted=0;
            if(sort===1){
              completeImageUrl='http://'+resImageUrl.data.ImageUrl;
            }
            await entityManager.save(UserLittleThingsImageEntity,newUserLittleThingsImageEntity)
          }
        }
        //#endregion

        //#region 更新UserLittleThingsExtend表
        const isExistData=await entityManager.count(UserLittleThingsExtendEntity,{
          where:{
            LittleSysID:SysID
          }
        })
        const weekly=computeWeekly(dayjs(CompleteTime).day());
        const completeDay=dayjs(CompleteTime).format('DD');
        const completeYearAndMonth=dayjs(CompleteTime).format('YYYY年MM月');
        if(isExistData===0){
          //新增
          const newUserLittleThingsExtendEntity = new UserLittleThingsExtendEntity();
          newUserLittleThingsExtendEntity.LittleSysID=SysID;
          newUserLittleThingsExtendEntity.CompleteAddress=CompleteAddress;
          newUserLittleThingsExtendEntity.CompleteTime=CompleteTime;
          newUserLittleThingsExtendEntity.Weekly=weekly;
          newUserLittleThingsExtendEntity.CompleteDay=completeDay;
          newUserLittleThingsExtendEntity.CompleteYearAndMonth=completeYearAndMonth;
          newUserLittleThingsExtendEntity.CompleteImageUrl=completeImageUrl;
          newUserLittleThingsExtendEntity.CreateTime=now;
          newUserLittleThingsExtendEntity.UpdateTime=now;
          newUserLittleThingsExtendEntity.Deleted=0;
          await entityManager.save(UserLittleThingsExtendEntity,newUserLittleThingsExtendEntity)
        }
        else{
          //修改
          const updateUserLittleThingsExtendEntity=new UserLittleThingsExtendEntity();
          updateUserLittleThingsExtendEntity.CompleteAddress=CompleteAddress;
          updateUserLittleThingsExtendEntity.CompleteTime=CompleteTime;
          updateUserLittleThingsExtendEntity.Weekly=weekly;
          updateUserLittleThingsExtendEntity.CompleteDay=completeDay;
          updateUserLittleThingsExtendEntity.CompleteYearAndMonth=completeYearAndMonth;
          updateUserLittleThingsExtendEntity.CompleteImageUrl=completeImageUrl;
          updateUserLittleThingsExtendEntity.UpdateTime=now;
          await entityManager.update(UserLittleThingsExtendEntity,{
            LittleSysID:SysID,
            Deleted:0
          },updateUserLittleThingsExtendEntity)
        }
        //#endregion

      })
      resData.msg='完成清单!'
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:''
      }
    }
    return resData
  }

  async getCompletedUserLittleThingsInfo(getCompletedUserLittleThingsInfo:GetCompletedUserLittleThingsInfoDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      console.log('778899')
      const {SysID=-1}=getCompletedUserLittleThingsInfo;
      const info=await this.userLittleThingsEntityRepository
        .createQueryBuilder('L')
        .select([
          'L.SysID SysID',`L.ThingName ThingName`,`L.ThingContent ThingContent`,
          `IFNULL(LE.CompleteTime,'') CompleteTime`,`IFNULL(LE.CompleteAddress,'') CompleteAddress`
        ])
        .leftJoin('UserLittleThingsExtend','LE','L.SysID=LE.LittleSysID AND LE.Deleted=0')
        .where('L.SysID=:SysID AND L.Deleted=0',{SysID:SysID})
        .getRawMany()
      if(info.length>0){
        const imageData=await this.userLittleThingsImageEntityRepository.find({
          select:['SysID','ImageUrl'],
          where:{
            LittleSysID:SysID,
            Deleted:0
          },
          order:{
            SysID:'ASC'
          }
        })
        resData.data={
          ...info[0],
          ImageData:imageData
        }
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取详情失败!'
      }
    }
    return resData
  }
}
